package com.quectel.core.module.propertybill.service.impl;


import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.core.propertybill.PropertyBillConstants;
import com.quectel.constant.core.propertybill.PropertyChargeableConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.propertybill.dao.PropertyChargeableListBindingDao;
import com.quectel.core.module.propertybill.dao.PropertyChargeableListDao;
import com.quectel.core.module.propertybill.dao.PropertyChargeableListItemBindingDao;
import com.quectel.core.module.propertybill.dto.PropertyChargeableItemDto;
import com.quectel.core.module.propertybill.dto.PropertyChargeableListBindingDto;
import com.quectel.core.module.propertybill.dto.PropertyChargeableListDto;
import com.quectel.core.module.propertybill.dto.PropertyChargeableListItemBindingDto;
import com.quectel.core.module.propertybill.entity.PropertyChargeableListBindingEntity;
import com.quectel.core.module.propertybill.entity.PropertyChargeableListEntity;
import com.quectel.core.module.propertybill.entity.PropertyChargeableListItemBindingEntity;
import com.quectel.core.module.propertybill.service.PropertyChargeableItemService;
import com.quectel.core.module.propertybill.service.PropertyChargeableListBindingService;
import com.quectel.core.module.propertybill.service.PropertyChargeableListItemBindingService;
import com.quectel.core.module.propertybill.service.PropertyChargeableListService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/03/31 14:36
 */
@DubboService
public class PropertyChargeableListServiceImpl implements PropertyChargeableListService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyChargeableListServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PROPERTY_CHARGEABLE_LIST_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PROPERTY_CHARGEABLE_LIST_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PropertyChargeableListDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PROPERTY_CHARGEABLE_LIST_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PropertyChargeableListDao propertyChargeableListDao;
    @Autowired
    private PropertyChargeableItemService propertyChargeableItemService;
    @Autowired
    private PropertyChargeableListBindingService propertyChargeableListBindingService;
    @Autowired
    private PropertyChargeableListItemBindingService propertyChargeableListItemBindingService;
    @Autowired
    private VillageService villageService;
    @Autowired
    private VillageBuildingService villageBuildingService;
    @Autowired
    private PropertyChargeableListBindingDao propertyChargeableListBindingDao;
    @Autowired
    private PropertyChargeableListItemBindingDao propertyChargeableListItemBindingDao;

    @Override
    public List<PropertyChargeableListDto> selectByTenantAndVillage(Long tenantId, Long villageId) {

        //查询小区所有的楼栋
        Map<String, Object> params = new HashMap<>(2);
        params.put(LambdaUtil.getFieldName(VillageBuildingDto::getTenantId), tenantId);
        params.put(LambdaUtil.getFieldName(VillageBuildingDto::getVillageId), villageId);
        List<VillageBuildingDto> villageBuildingDtos = villageBuildingService.queryList(params);
        if (CollectionUtils.isEmpty(villageBuildingDtos)) {
            return null;
        }
        List<Long> collect = villageBuildingDtos.stream().map(VillageBuildingDto::getId).collect(Collectors.toList());

        //查询
        Map<String, Object> buildingParams = new HashMap<>(1);
        buildingParams.put(PropertyBillConstants.BINDING_IDS, collect);
        buildingParams.put(LambdaUtil.getFieldName(PropertyChargeableListBindingDto::getBindingType), PropertyChargeableConstant.SourceType.VILLAGE.getType());
        List<PropertyChargeableListBindingDto> propertyChargeableListBindingDtos = propertyChargeableListBindingService.queryList(buildingParams);

        Set<Long> chargeableListIs = propertyChargeableListBindingDtos.stream().map(PropertyChargeableListBindingDto::getChargeableListId).collect(Collectors.toSet());

        List<PropertyChargeableListDto> propertyChargeableListDtos = new ArrayList<>();
        for (Long chargeableListId : chargeableListIs) {
            propertyChargeableListDtos.add(selectCacheById(chargeableListId));
        }

        return propertyChargeableListDtos;
    }

    @Override
    public List<PropertyChargeableListDto> selectByBuildingId(Long buildingId) {
        Map<String, Object> buildingParams = new HashMap<>(2);
        buildingParams.put(LambdaUtil.getFieldName(PropertyChargeableListBindingDto::getBindingType), PropertyChargeableConstant.SourceType.VILLAGE.getType());
        buildingParams.put(LambdaUtil.getFieldName(PropertyChargeableListBindingDto::getBindingId), String.valueOf(buildingId));
        List<PropertyChargeableListBindingDto> buildingBindingList = propertyChargeableListBindingService.queryList(buildingParams);

        Set<Long> collect = buildingBindingList.stream().map(PropertyChargeableListBindingDto::getChargeableListId).collect(Collectors.toSet());
        List<PropertyChargeableListDto> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(collect)) {
            for (Long aLong : collect) {
                PropertyChargeableListDto propertyChargeableListDto = selectCacheById(aLong);
                list.add(propertyChargeableListDto);
            }
        }

        return list;
    }

    /**
     * save or update
     * 标准绑定楼栋信息
     * 标准绑定项目信息
     *
     * @param propertyChargeableListDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(PropertyChargeableListDto propertyChargeableListDto) {
        if (propertyChargeableListDto.getId() == null) {
            Long id = save(propertyChargeableListDto);
            propertyChargeableListDto.setId(id);
        } else {
            updateById(propertyChargeableListDto);
        }

        propertyChargeableListBindingDao.delete(new LambdaQueryWrapper<PropertyChargeableListBindingEntity>()
                .eq(PropertyChargeableListBindingEntity::getChargeableListId, propertyChargeableListDto.getId()));
        propertyChargeableListItemBindingDao.delete(new LambdaQueryWrapper<PropertyChargeableListItemBindingEntity>()
                .eq(PropertyChargeableListItemBindingEntity::getChargeableListId, propertyChargeableListDto.getId()));

        // 如果是楼栋 保存关系
        for (VillageBuildingDto buildingDto : propertyChargeableListDto.getBuildingList()) {
            PropertyChargeableListBindingDto gridBinding = new PropertyChargeableListBindingDto();
            gridBinding.setId(Snowflake.nextId());
            gridBinding.setChargeableListId(propertyChargeableListDto.getId());
            gridBinding.setBindingType(GridConstant.SourceType.BUILDING.getType());
            gridBinding.setBindingId(buildingDto.getId());
            propertyChargeableListBindingService.save(gridBinding);
        }


        // 项目关联标准
        for (PropertyChargeableItemDto propertyChargeableItemDto : propertyChargeableListDto.getItemList()) {
            PropertyChargeableListItemBindingDto listItemBinding = new PropertyChargeableListItemBindingDto();
            listItemBinding.setId(Snowflake.nextId());
            listItemBinding.setChargeableItemId(propertyChargeableItemDto.getId());
            listItemBinding.setChargeableListId(propertyChargeableListDto.getId());
            propertyChargeableListItemBindingService.save(listItemBinding);
        }
    }

    @Override
    public PropertyChargeableListDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PROPERTY_CHARGEABLE_LIST_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PropertyChargeableListDto selectById(Long id) {
        PropertyChargeableListEntity entity = propertyChargeableListDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, PropertyChargeableListDto.class));
    }

    @Override
    public List<PropertyChargeableListDto> queryList(Map<String, Object> params) {
        List<PropertyChargeableListEntity> list = propertyChargeableListDao.queryList(params);
        List<PropertyChargeableListDto> result = CopyUtils.copyList(list, PropertyChargeableListDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PropertyChargeableListDto paddingField(PropertyChargeableListDto dto) {
        if (dto != null) {
            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                if (villageDto != null) {
                    dto.setVillageName(villageDto.getName());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return propertyChargeableListDao.queryTotal(params);
    }

    @Override
    public Long save(PropertyChargeableListDto dto) {
        PropertyChargeableListEntity entity = CopyUtils.copyObj(dto, PropertyChargeableListEntity.class);
        entity.setId(Snowflake.nextId());
        propertyChargeableListDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PropertyChargeableListDto dto) {
        PropertyChargeableListEntity entity = CopyUtils.copyObj(dto, PropertyChargeableListEntity.class);

        propertyChargeableListDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PropertyChargeableListDto dto) {
        PropertyChargeableListEntity entity = CopyUtils.copyObj(dto, PropertyChargeableListEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, propertyChargeableListDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        propertyChargeableListDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
